package com.ljj.controller;/**
 * @FileName: BuyerProductController.java
 * @Package: com.ljj.controller
 * @Author: lijiajun
 * <br/>
 * @Created: 2018/3/23 11:23
 */

import com.ljj.VO.ProductInfoVO;
import com.ljj.VO.ProductVO;
import com.ljj.VO.ResultVO;
import com.ljj.dataobject.ProductCategory;
import com.ljj.dataobject.ProductInfo;
import com.ljj.service.IProductCategoryService;
import com.ljj.service.IProductInfoService;
import com.ljj.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *买家端商品显示
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private IProductInfoService productInfoService;

    @Autowired
    private IProductCategoryService productCategoryService;

    @GetMapping("/list")
    @Cacheable(cacheNames = "productList",key = "1")
    public ResultVO list(){
        //1,查询所有上架的商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        //2,查询类目
        //获得上架商品的类目编号
        List<Integer> categoryTypeList = new ArrayList<>();
        //传统方法
        for (ProductInfo productInfo : productInfoList){
            categoryTypeList.add(productInfo.getCategoryType());
        }
        //lambda

        //根据上架商品类目编号得到商品类目
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeList);
        //3,拼装数据
        //拼装productVO
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList){
            //设置productVO的类目名称和编号
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoeyType(productCategory.getCategoryType());

            //拼装productInfoVO
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList){
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo , productInfoVO);
                    //添加到productInfoVO集合中
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoList(productInfoVOList);

            //添加到productVO集合中
            productVOList.add(productVO);
        }
//        return ResultVOUtil.error("失败了");
        return ResultVOUtil.success(productVOList);
    }

}